# Definition for singly-linked list.
from typing import Optional
"""
    给你两个单链表的头节点 headA 和 headB ，
    请你找出并返回两个单链表相交的起始节点。
    如果两个链表不存在相交节点，返回 null 。
    图示两个链表在节点 c1 开始相交：
"""

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        lenA, lenB = 0, 0
        tem1, tem2 = headA, headB
        while tem1 or tem2:
            if tem1:
                lenA += 1
                tem1 = tem1.next
            if tem2:
                lenB += 1
                tem2 = tem2.next

        if lenA > lenB:
            for i in range(lenA - lenB):
                headA = headA.next
        if lenB > lenA:
            for i in range(lenB - lenA):
                headB = headB.next

        while headA and headA != headB:
            headA = headA.next
            headB = headB.next

        return headA
